<?php

namespace App\Http\Controllers\Api;

use App\Models\Book;
use App\Models\Bookshelf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use App\Http\Resources\Book as BookCollection;

class BookShelfController extends ApiController
{




    function __construct()
    {
        $this->middleware('auth:api')->only([
            'destroy',
            'search',
            'store'
        ]);

    }

    /**
     *
     * @api {get} bookshelf/search 搜索书架
     * @apiName Bookshelf search
     * @apiGroup Bookshelf
     *
     * @apiParam {String} qw 关键字
     * @apiParam {String} [limit] 限制的条数
     * @apiParam {String} [page] 当前的页数
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/bookshelf/search
     *
     */
    public function search(){

        $qw = Input::get('qw');

        $limit = Input::get('limit') ?: 20;

        $user = Auth::user();

        $books = $user->shelf()->where('name','like','%'.$qw.'%')->paginate($limit);

        return BookCollection::collection($books);

    }


    public function store(Request $request){

        $this->validate($request,[

            'book_id' => 'required|exists:books,id'

        ]);

        $book = Book::find($request->book_id);

        $user = Auth::user();

        $shelf = Bookshelf::where('book_num',$book->book_num)
            ->where('uid',$user->id)
            ->first();

        if ($shelf){
                $shelf->update([
                    'status' => 0,
                    'cancel_time' => 0
                ]);
            return $this->message('添加成功');

        }

        $user->shelf()->attach([

            'book_num' => $book->book_num

        ],[
            'join_time' => time(),
            'cancel_time' => 0
        ]);

        return $this->message('添加成功');
    }


    /**
     *
     * @api {delete} /bookshelf 删除书架的书籍
     * @apiName BookShelf delete
     * @apiGroup BookShelf
     *
     *
     * @apiParam {String} book_nums[] 书籍编号的数组
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /bookshelf
     *
     * @apiSuccessExample {json} Success-Response:
     *
     *  {
     *       "status": "success",
     *       "code": 200,
     *       "data": "删除成功"
     *   }
     */
    public function destroy(Request $request){

        $this->validate($request,[
            'book_nums' => 'required',
            'book_nums.*' => 'exists:books,book_num'
        ]);

        $user = Auth::user();

        $book_nums = $request->get('book_nums');


        Bookshelf::whereIn('book_num',$book_nums)
        ->where('uid',$user->id)
        ->where('status',0)
        ->update([
            'status' => 1,
            'cancel_time' => time()
        ]);

        return $this->message('删除成功');

    }

}
